from database.connectorMysq import DatabaseUtils
from model.tools import compareUserTokens
from config.config import mysqlConfig
from flask import jsonify

db_utils = DatabaseUtils(
    pool_name='navbg',
    host=mysqlConfig["host"],
    user=mysqlConfig["user"],
    password=mysqlConfig["password"],
    database=mysqlConfig["database"]
)


def getBackgroundImage(category, isHome):
    try:
        with db_utils.get_connection() as connection:
            if category == "all":
                query = "SELECT id,category,background_image FROM background"
            else:
                if isHome == "T":
                    query = "SELECT background_image FROM background WHERE category = '{}'".format(category)
                else:
                    query = "SELECT id,category,background_image FROM background WHERE category = '{}'".format(category)
            with connection.cursor() as cursor:
                cursor.execute(query)
                data = cursor.fetchall()
            if isHome == "T":
                return data
            else:
                jsons = [{
                    "id": item[0],
                    "category": item[1],
                    "background_image": item[2],
                } for item in data]
                return jsonify(jsons)
    except Exception as e:
        print(e)
        return "获取失败"


def delBackground(userid, navid, token):
    try:
        with db_utils.get_connection() as connection:
            if not compareUserTokens(connection, userid, token):
                return {"msg": "token已经过期，请重新获取"}

            query = "DELETE FROM background WHERE id = %s"
            data = (navid,)

            with connection.cursor() as cursor:
                cursor.execute(query, data)
                connection.commit()

            return "删除成功"
    except Exception as e:
        print(e)
        return "删除未成功"


def addBackground(userid, category, img, token):
    try:
        with db_utils.get_connection() as connection:
            if not compareUserTokens(connection, userid, token):
                return {"msg": "token已经过期，请重新获取"}

            query = "INSERT INTO background (category, background_image) VALUES (%s, %s)"
            data = (category, img)

            with connection.cursor() as cursor:
                cursor.execute(query, data)
                connection.commit()

            result = {
                "msg": "增加成功"
            }
            return result
    except Exception as e:
        print(e)
        result = {
            "msg": "增加失败，请稍后重试"
        }
        return result